<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\common\model\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Withdraw;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $map = [];
            if ($this->auth->id != 1){
                $map['uid'] = $this->auth->id;
            }

            $list = $this->model
                    ->with(['admin','card'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['username','nickname']);
                // $row->getRelation('card')->visible(['name','bank','card']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $money = Db::name("admin")->where('id',$this->auth->id)->value("money");
        $money = bcdiv($money,100,2);
        $this->assign("money",$money);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if(floatval($params['money']) <= 0) return $this->error("金额错误");

        $uid = $this->auth->id;
        // 费率默认3%
        $scale = config('site.withdraw_scale', 3);
        $scale = intval($scale * 100);
        if($this->auth->isSuperAdmin()){
            if($params['uid'] < 1) return $this->error("请选择商户");
            $uid = intval($params['uid']);
        }
        $beforemoney = Db::name("admin")->where('id',$uid)->value("money");
        $money = $params['money']*100;
        if($scale > 0) {
            $fee = intval($money * $scale / 10000);
            $money += $fee;
        }
        if ($beforemoney < $money){
            $this->error("余额不足");
        }

        $insert = [
            'money' => $money,
            'before' => $beforemoney,
            'after' => $beforemoney - $money,
            'status' => 0,
            'uid' => $uid,
            'scale' =>  $scale,
            'cid' =>  $params['cid'],
        ];

        // 启动事务
        Db::startTrans();
        try{
            $this->model->allowField(true)->save($insert);
            Db::name("admin")->where('id',$uid)->update(["money"=>($beforemoney - $money)]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();

    }

    public function check($id){
        $withdraw = $this->model->where('id', $id)->find();
        if(!$withdraw) return $this->error("记录不存在");
        if($withdraw->type != 2) return $this->error("类型错误");
        if($withdraw->status != 0) return $this->error("状态错误");
        $withdraw->status = 1;
        $withdraw->save();
        return $this->success();
    }

}